package com.yonyou.pmclouds.comprehensiveacceptance.process;

import com.yonyou.pmclouds.basecom.billstatus.BillStatusConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.yonyou.pmclouds.basecom.bp.processor.SingleProcessor;
import com.yonyou.pmclouds.basecom.consts.BillTypeConst;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.comprehensiveacceptance.entity.AcceptancePassStatusEnum;
import com.yonyou.pmclouds.comprehensiveacceptance.entity.ComprehensiveAcceptanceVO;
import com.yonyou.pmclouds.comprehensiveacceptance.rmiitf.ComprehensiveAcceptanceQuery;
import com.yonyou.pmclouds.inspectitem.entity.InspectItemBillStatusConst;
import com.yonyou.pmclouds.inspectitem.entity.InspectItemVO;

@Component
public class ComprehensiveAcceptanceBeforeInsertProcess implements SingleProcessor<ComprehensiveAcceptanceVO> {
	@Autowired
    private ComprehensiveAcceptanceQuery acceptanceQuery;
    @Override
    public void process(ComprehensiveAcceptanceVO vo, ComprehensiveAcceptanceVO orig) throws BusinessException {
    	// 此处应该校验是否已经存在通过的的验收单
		ComprehensiveAcceptanceVO[] acceptanceVOs = acceptanceQuery.queryByProject(vo.getPkProject());
		for (ComprehensiveAcceptanceVO comprehensiveAcceptanceVO : acceptanceVOs) {
			if(comprehensiveAcceptanceVO.getBillstatus() == BillStatusConst.COMMON_APPROVED_STATUS ||
					comprehensiveAcceptanceVO.getBillstatus() == BillStatusConst.COMMON_APPROVING_STATUS) {
				throw new BusinessException("该项目的综合验收已完成，可以到项目详情中查看详情!");
			}
		}
		// 查看是否全部合格，如果全部合格就设置为通过验收状态
		boolean isPass = true;
		int notFitNum = 0;
		InspectItemVO[] inspectItems = vo.getInspectitems();

		if(inspectItems != null && inspectItems.length > 0){
			for (InspectItemVO inspectItemVO : inspectItems) {
				if(InspectItemBillStatusConst.BILLSTATUS_NOT_FIT == inspectItemVO.getBillstatus()){
					notFitNum ++;
				}
				if(InspectItemBillStatusConst.BILLSTATUS_NO_PASS == inspectItemVO.getBillstatus()) {
					isPass = false;
					break;
				}
			}

			if(isPass && notFitNum != inspectItems.length) {
				vo.setAcceptanceStatus((byte) AcceptancePassStatusEnum.PASS.getCode());
			} else {
				vo.setAcceptanceStatus((byte) AcceptancePassStatusEnum.NO_PASS.getCode());
			}
		}

        // 设置单据类型
        vo.setBillType(BillTypeConst.COMPREHENSIVE_ACCEPTANCE_BILLTYPE);
		vo.setBillstatus(BillStatusConst.COMMON_FREE_STATUS);
    }

}
